﻿//layui.use(function () {
//    var table = layui.table;
//    var layer = layui.layer;
//    var $ = layui.jquery;
$(function () {
    Show()
})

//生产列表
function Show() {
    layui.use(function () {
        var table = layui.table;
        var layer = layui.layer; 
        var $ = layui.jquery;
        var productiongNumbering = $("#productiongNumbering").val();
        var productionstate = $("#productionstate").val();
        var productionDate = $("#productionDate").val();

        console.log(table)
        // 先进行表格的初始渲染
        table.render({
            elem: '#carriertable',  // 表格元素的选择器
            page: {
                limit: 5,
                limits: [3, 5, 8, 10]
            },
            toolbar: '#toolbarDemo',
            defaultToolbar: ['exports'],
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'productionSerialNumber', title: '序号' },
                { field: 'theProductionPlanNumber', title: '生产计划编号' },
                {
                    field: 'productionStatus', title: '生产状态', templet: function (d) {
                        return d.productionStatus == 1 ? '已排程' : '未排程';
                    }

                },
                { field: 'theFinishedProduct', title: '成品编号' },
                {
                    field: 'myProperty', title: '优先级', templet: function (d) {
                        return d.myProperty == 1 ? '<span style="color: red;">紧急</span>' : '<span style="color: green;">不紧急</span>';;
                    }
                },
                { field: 'specificationsAndModels', title: '规格型号' },
                { field: 'plannedProduction', title: '计划产量' },
                { field: 'numberReportedJobs', title: '报工数量' },
                { field: 'orderNumber', title: '订单编号' },


                {
                    field: 'deliveryDate', title: '交付日期', templet: function (d) {
                        return formatTime2(d.deliveryDate); // 调用自定义的时间格式转换函数
                    }
                },


                {
                    field: 'routing', title: '工艺路线', templet: function (d) {
                        var locations = ['', '工艺一', '工艺二'];
                        return locations[d.routing];
                    }
                },
                {
                    field: 'workShop', title: '车间', templet: function (d) {
                        var locations = ['', '车间一', '车间二', '车间三'];
                        return locations[d.workShop];
                    }
                },
                {
                    field: 'planTheStartTime', title: '计划开始日期', templet: function (d) {
                        return formatTime(d.planTheStartTime); // 调用自定义的时间格式转换函数
                    }
                },
                {
                    field: 'scheduledEndTime', title: '计划结束日期', templet: function (d) {
                        return formatTime(d.scheduledEndTime); // 调用自定义的时间格式转换函数
                    }
                },
                //{
                //    field: 'actualStartTime', title: '实际开始日期', templet: function (d) {
                //        return formatTime(d.actualStartTime); // 调用自定义的时间格式转换函数
                //    }
                //},
                //{
                //    field: 'actualEndTime', title: '实际结束日期', templet: function (d) {
                //        return formatTime(d.actualEndTime); // 调用自定义的时间格式转换函数
                //    }
                //},
                { field: 'addName', title: '创建人' },
                {
                    field: 'addTime', title: '创建时间', templet: function (d) {
                        return formatTime(d.addTime); // 调用自定义的时间格式转换函数
                    }
                },
                {
                    field: '', title: '操作', templet: function (d) {
                        return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.productionId + ')"><i class="layui-icon layui-icon-edit"></i>排程</a> ' + '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editUpdate(' + d.productionId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                            '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.productionId + ')"><i class="layui-icon layui-icon-delete"></i>作废</a>';
                    }
                }
            ]],
            // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
            // +
            //'<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="stateData(' + d.equipmentId + ')"><i class="layui-icon layui-icon-delete"></i>恢复</a>
            data: []
        });
        // 创建表格实例
        $.ajax({
            url: "/ProductionPlanning/ProductionPlanningsShow",
            type: "get",
            data: {
                pageIndex: 1,
                pageSize: 100,
                theProductionPlanNumber: productiongNumbering,
                productionStatus: productionstate || 0,
                deliveryDate: productionDate,
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data.data.pageList);
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('carriertable', {
                    page: {
                        limit: 5,
                        limits: [3, 5, 8, 10]
                    },
                    data: data.data.pageList
                });
            },
            error: function () {
                console.log("请求失败");
            }
        });
    });
}


//排程跳转按钮
window.editData = function (productionId) {
    localStorage["productionId"] = productionId
    location.href = "/ProductionPlanning/ProductionPlanningsFind";
}


//生产作废
window.deleteData = function (productionId) {
    console.log(productionId);
    layer.confirm('该生产计划正在进行中，确定作废吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/ProductionPlanning/ProductionPlanningsDelete",  // 替换为实际的后台删除数据接口地址
            data: { data: JSON.stringify({ productionId: productionId }), token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.data >= 1) {
                    layer.alert("作废成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("作废失败");

                }
            },
            error: function () {
                layer.msg('作废失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

//修改
var obj = {
    productionId: '',            //生产ID
    productionSerialNumber: '',  //生产序号
    theProductionPlanNumber: '', //生产计划编号
    productionStatus: '',        //生产状态
    theFinishedProduct: '',      //产品编号
    myProperty: '',              //优先级
    specificationsAndModels: '', //规格型号
    plannedProduction: '',       //计划产量
    numberReportedJobs: '',      //报工数量
    orderNumber: '',             //订单编号
    deliveryDate: '',            //交付日期
    routing: '',                 //工艺路线
    workShop: '',                //车间
    planTheStartTime: '',        //计划开始日期
    scheduledEndTime: '',        //计划结束日期
    //actualStartTime: '',         //实际开始日期
    //actualEndTime: '',           //实际结束日期
    addName: '',                 //添加人
    addTime: ''                  //添加时间
}

window.editUpdate = function (productionId) {
    console.log(productionId)
    // 先根据id获取要编辑的数据，发起Ajax请求
    var form = layui.form;
    $.ajax({
        type: "get",
        url: "/ProductionPlanning/ProductionPlanningsFinds",  // 替换为实际的后台根据id获取数据的接口地址
        data: { productionId: productionId, token: localStorage.getItem("token") },
        success: function (res) {
            var res = JSON.parse(res)
            console.log(res)
            $(res.data).each(function () {
                console.log(this.productionSerialNumber)
                //$('#productionId').val(this.productionId);
                $('#productionSerialNumber').val(this.productionSerialNumber);
                $('#theProductionPlanNumber').val(this.theProductionPlanNumber);
                // 反填生产状态单选框
                var productionStatus = this.productionStatus;
                $('input[name="productionStatus"][value="' + productionStatus + '"]').prop('checked', true);
                $('#theFinishedProduct').val(this.theFinishedProduct);
                // 反填优先级单选框
                var myProperty = this.myProperty;
                $('input[name="myProperty"][value="' + myProperty + '"]').prop('checked', true);
                $('#specificationsAndModels').val(this.specificationsAndModels);
                $('#plannedProduction').val(this.plannedProduction);
                $('#numberReportedJobs').val(this.numberReportedJobs);
                $('#orderNumber').val(this.orderNumber);
                // 反填交付日期
                const dateValue = this.deliveryDate;
                const date = new Date(dateValue);
                if (!isNaN(date.getTime())) {
                    const formattedDate = date.toISOString().split('T')[0];
                    document.getElementById('deliveryDate').value = formattedDate;
                } else {
                    document.getElementById('deliveryDate').value = ''; // 或者其他
                }
                $('#routing').val(this.routing);
                $('#workShop').val(this.workShop);
                //反填下拉框要渲染
                form.render('select');
                // 反填计划开始日期
                const dateValue2 = this.planTheStartTime;
                const date2 = new Date(dateValue2);
                if (!isNaN(date2.getTime())) {
                    const formattedDate = date2.toISOString().split('T')[0];
                    document.getElementById('planTheStartTime').value = formattedDate;
                } else {
                    document.getElementById('planTheStartTime').value = ''; // 或者其他
                }
                // 反填计划结束日期
                const dateValue3 = this.scheduledEndTime;
                const date3 = new Date(dateValue3);
                if (!isNaN(date3.getTime())) {
                    const formattedDate = date3.toISOString().split('T')[0];
                    document.getElementById('scheduledEndTime').value = formattedDate;
                } else {
                    document.getElementById('scheduledEndTime').value = ''; // 或者其他
                }


                obj.productionId = this.productionId
                obj.productionSerialNumber = this.productionSerialNumber
                obj.theProductionPlanNumber = this.theProductionPlanNumber
                obj.productionStatus = this.productionStatus
                obj.theFinishedProduct = this.theFinishedProduct
                obj.myProperty = this.myProperty
                obj.specificationsAndModels = this.specificationsAndModels
                obj.plannedProduction = this.plannedProduction
                obj.numberReportedJobs = this.numberReportedJobs
                obj.orderNumber = this.orderNumber
                obj.deliveryDate = this.deliveryDate
                obj.routing = this.routing
                obj.workShop = this.workShop
                obj.planTheStartTime = this.planTheStartTime
                obj.scheduledEndTime = this.scheduledEndTime
                obj.addName = this.addName
                obj.addTime = this.addTime 
                debugger
            })
        },
    });

    layer.open({
        type: 1,
        title: '编辑生产信息',
        content: `<form class="layui-form" style="padding:30px;">
                     <div class="layui-form-item">
                    <label class="layui-form-label">生产序号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="productionSerialNumber" autocomplete="off" id="productionSerialNumber" placeholder="请输入生产序号" class="layui-input">
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">生产计划编号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="theProductionPlanNumber" autocomplete="off" id="theProductionPlanNumber" placeholder="请输入生产计划编号" class="layui-input">
                    </div>
                    </div>

                      <div class="layui-form-item">
                   <label class="layui-form-label">状态: </label>
                   <div class="layui-input-inline">
                       <input type="radio" name="workshopState"  value="1" checked>正常
                       <input type="radio" name="workshopState"  value="2">异常
                   </div>
                   </div>

                    <div class="layui-form-item">
                    <label class="layui-form-label">产品编号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="theFinishedProduct" autocomplete="off" id="theFinishedProduct" placeholder="请输入生产产品编号" class="layui-input">
                    </div>
                    </div>

                       <div class="layui-form-item">
                   <label class="layui-form-label">优先级: </label>
                   <div class="layui-input-inline">
                       <input type="radio" name="myProperty"  value="1" checked>紧急
                       <input type="radio" name="myProperty"  value="2">不紧急
                   </div>
                   </div>

                    <div class="layui-form-item">
                    <label class="layui-form-label">规格型号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="specificationsAndModels" autocomplete="off" id="specificationsAndModels" placeholder="请输入规格型号" class="layui-input">
                    </div>
                    </div>

                     <div class="layui-form-item">
                    <label class="layui-form-label">生产计划产量：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="plannedProduction" autocomplete="off" id="plannedProduction" placeholder="请输入生产计划产量" class="layui-input">
                    </div>
                    </div>

                     <div class="layui-form-item">
                    <label class="layui-form-label">报工数量：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="numberReportedJobs" autocomplete="off" id="numberReportedJobs" placeholder="请输入报工数量" class="layui-input">
                    </div>
                    </div>

                    <div class="layui-form-item">
                    <label class="layui-form-label">订单编号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="orderNumber" autocomplete="off" id="orderNumber" placeholder="请输入订单编号" class="layui-input">
                    </div>
                    </div>

                     <div class="layui-inline">
                    <label class="layui-form-label">交付日期</label>
                    <div class="layui-input-inline">
                        <input type="date" class="layui-input" name="deliveryDate" id="deliveryDate" placeholder="yyyy-MM-dd" lay-verify="date">
                    </div>
                    </div>
                    </br>

                      <div class="layui-form-item">
                   <label class="layui-form-label">工艺路线：</label>
                   <div class="layui-input-inline">
                       <select name="routing" id="routing" required lay-verify="required">
                           <option value="">请选择</option>
                           <option value="1">工艺一</option>
                           <option value="2">工艺二</option>
                       </select>
                   </div>
                    </div>

                     <div class="layui-form-item">
                   <label class="layui-form-label">车间位置：</label>
                   <div class="layui-input-inline">
                       <select name="workShop" id="workShop" required lay-verify="required">
                           <option value="">请选择</option>
                           <option value="1">位置一</option>
                           <option value="2">位置二</option>
                           <option value="3">位置三</option>
                       </select>
                   </div>
                    </div>
                   

                      <div class="layui-inline">
                    <label class="layui-form-label">计划开始日期</label>
                    <div class="layui-input-inline">
                        <input type="date" class="layui-input" name="planTheStartTime" id="planTheStartTime" placeholder="yyyy-MM-dd" lay-verify="date">
                    </div>
                </div>
                </br>

                 <div class="layui-inline">
                    <label class="layui-form-label">计划结束日期</label>
                    <div class="layui-input-inline">
                        <input type="date" class="layui-input" name="scheduledEndTime" id="scheduledEndTime" placeholder="yyyy-MM-dd" lay-verify="date">
                    </div>
                </div>
                    <div class="layui-input-block">
                    <button class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                     <button class="layui-btn" lay-submit lay-filter="demo-login">修改</button>
                    </div>
                    <form>
                    `,
        area: ['700px', '400px'],
        success: function () {
            var obj1 = {
                productionId: '',            //生产ID
                productionSerialNumber: '',  //生产序号
                theProductionPlanNumber: '', //生产计划编号
                productionStatus: '',        //生产状态
                theFinishedProduct: '',      //产品编号
                myProperty: '',              //优先级
                specificationsAndModels: '', //规格型号
                plannedProduction: '',       //计划产量
                numberReportedJobs: '',      //报工数量
                orderNumber: '',             //订单编号
                deliveryDate: '',            //交付日期
                routing: '',                 //工艺路线
                workShop: '',                //车间
                planTheStartTime: '',        //计划开始日期
                scheduledEndTime: '',        //计划结束日期
                //actualStartTime: '',         //实际开始日期
                //actualEndTime: '',           //实际结束日期
                addName: '',                 //添加人
                addTime: ''                  //添加时间
            };
            console.log(obj1)
            // 对弹层中的表单进行初始化渲染

            form.render();
             //表单提交事件
            form.on('submit(demo-login)', function (data) {
                var field = data.field;

                obj1.productionId = obj.productionId
                obj1.productionSerialNumber = field.productionSerialNumber
                obj1.theProductionPlanNumber = field.theProductionPlanNumber
                obj1.productionStatus = field.productionStatus
                obj1.theFinishedProduct = field.theFinishedProduct
                obj1.myProperty = field.myProperty
                obj1.specificationsAndModels = field.specificationsAndModels
                obj1.plannedProduction = field.plannedProduction
                obj1.numberReportedJobs = field.numberReportedJobs
                obj1.orderNumber = field.orderNumber
                obj1.deliveryDate = field.deliveryDate
                obj1.routing = field.routing
                obj1.workShop = field.workShop
                obj1.planTheStartTime = field.planTheStartTime
                obj1.scheduledEndTime = field.scheduledEndTime
                obj1.addName = obj.addName
                obj1.addTime = obj.addTime
                $.ajax({
                    url: '/ProductionPlanning/ProductionPlanningsUpdate',
                    type: 'post',
                    data: { obj1, token: localStorage.getItem("token") },
                    success: function (res) {
                        var res = JSON.parse(res)
                        console.log(field)
                        console.log(res)
                        if (res.data >= 1) {
                            layer.alert("修改成功");
                            setTimeout(function () {
                                location.reload();
                            }, 2000);
                        }
                        else {
                            layer.alert("修改失败");
                        }
                    }
                })
                return false; // 阻止默认 form 跳转
            });
        }
    });
};

// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp); 
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
} 

function formatTime2(timeStamp1) {
    if (timeStamp1) {
        var date = new Date(timeStamp1);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return year + '-' + month + '-' + day;
    }
    return "";
}


//});



